<template>
  <div>
    <!-- 头部 -->
    <div class="head">
      <div class="content">
        <img
          class="textimg"
          src="../../assets/Application/textfengzhuang.png"
          alt=""
        />

        <div class="circle">
          <div class="btns">
            <el-button
              type="primary"
              class="shop"
              @click="$router.push('/priceMoney')"
              >购买套餐</el-button
            >
            <el-button
              type="primary"
              class="upload"
              @click="dialogVisible = true"
              >立即封装</el-button
            >
          </div>
        </div>
      </div>
    </div>

    <!--底部 -->
    <div class="bottom">
      <!-- 搜索 -->
      <div class="search">
        <div>
          <el-select v-model="phoneModel">
            <el-option
              v-for="item in phoneModelList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>

          <el-input
            class="seek"
            v-model="seek"
            style="width: 220px"
            placeholder="请输入应用名称"
            suffix-icon="el-icon-search"
          ></el-input>
        </div>
        <div class="info">
          <div class="item">
            <div>应用存储空间容量</div>
            <div class="red">
              <div>
                {{ userInfo.in_spaceuse }} / {{ userInfo.in_spacetotal }}
              </div>
            </div>
          </div>

          <div class="item">
            <div>下载点数</div>
            <div class="red">{{ userInfo.in_points }}</div>
          </div>

          <div class="item">
            <div>会员等级</div>
            <div class="red">{{ userInfo.in_svip }}</div>
            <div class="red" v-if="userInfo.in_viptime">
              到期时间 {{ userInfo.in_viptime.split(' ')[0] }}
            </div>
          </div>
        </div>
        <!-- ==== -->
      </div>

      <!-- 列表 -->
      <div class="list">
        <el-table
          :data="newTableData"
          style="width: 100%"
          :header-cell-style="{
            background: '#F4F7FF',
            color: '#7F84A5',
            textAlign: 'center',
          }"
        >
          <el-table-column prop="name" label="名称" align="center" width="80">
          </el-table-column>
          <el-table-column
            prop="version"
            label="版本"
            align="center"
            width="100"
          >
          </el-table-column>
          <el-table-column label="大小" align="center" width="100">
            <template slot-scope="scope">
              {{ bytesToMB(scope.row.size) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="url"
            label="网站链接"
            align="center"
            width="180"
          >
          </el-table-column>
          <el-table-column
            prop="period"
            label="有效期"
            align="center"
            width="180"
          >
          </el-table-column>
          <el-table-column
            prop="in_applock"
            label="类型"
            align="center"
            width="100"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.type === 0">Android</div>
              <div v-if="scope.row.type === 1">i0S</div>
              <div v-if="scope.row.type === 2">iOS免签</div>
            </template>
          </el-table-column>
          <el-table-column prop="in_id" label="操作" align="center" width="400">
            <template slot-scope="scope">
              <el-button
                class="blue-button"
                @click="onUpdate(scope.row.id)"
                plain
                >发布</el-button
              >
              <el-button class="red-button" plain @click="onDel(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="应用名称" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="应用图标">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="(file) => handleAvatarSuccess(file, 1)"
            :show-file-list="false"
          >
            <img v-if="icon !== ''" :src="icon" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="应用地址" prop="url">
          <el-input v-model="ruleForm.url"></el-input>
        </el-form-item>
        <el-form-item label="应用启动图">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="(file) => handleAvatarSuccess(file, 2)"
            :show-file-list="false"
          >
            <img v-if="launch" :src="launch" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="手机类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择手机类型">
            <el-option label="Android" value="0"></el-option>
            <el-option label="iOS" value="1"></el-option>
            <el-option label="iOS免签" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="套餐选项：" prop="option">
          <el-radio-group v-model="ruleForm.option">
            <el-radio label="0">100</el-radio>
            <el-radio label="1">288</el-radio>
            <el-radio label="2">558</el-radio>
            <el-radio label="3">1088</el-radio>
            <el-radio label="4">2088</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="包名">
          <el-input
            v-model="ruleForm.bundle_id"
            placeholder="(选填)"
          ></el-input>
        </el-form-item>
        <el-form-item label="版本号">
          <el-input v-model="ruleForm.version" placeholder="(选填)"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >立即封装</el-button
          >
          <el-button @click="resetForm('ruleForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  app_pack_list,
  app_pack_publish,
  app_pack_del,
  uploadImageApi,
  app_pack,
} from '@/api/webpackaging';
import * as qiniu from 'qiniu-js';
import { getToken } from '@/api/fenfa';
export default {
  data() {
    return {
      userInfo: {},
      token: '',
      ruleForm: {
        name: '',
        url: '',
        type: '0',
        option: '',
        bundle_id: '',
        version: '',
        icon: '',
        launch: '',
      },
      rules: {
        name: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
        url: [{ required: true, message: '请输入应用网址', trigger: 'blur' }],
        type: [
          { required: true, message: '请选择手机类型', trigger: 'change' },
        ],
        option: [{ required: true, message: '请选择套餐', trigger: 'change' }],
      },
      dialogVisible: false,
      //手机机型列表
      phoneModelList: [
        {
          value: '全部',
          label: '全部',
        },
        {
          value: 0,
          label: '安卓',
        },
        {
          value: 1,
          label: 'IOS',
        },
        {
          value: 2,
          label: 'IOS免签',
        },
      ],
      //手机机型
      phoneModel: '全部',
      //搜索
      seek: '',
      //应用分发列表
      tableData: [],
      icon: '',
      launch: '',
    };
  },
  async created() {
    this.getList();
    this.token = (await getToken()).data;
    this.userInfo = this.$store.state.user;
    // console.log(this.token)
    // this.$watch('ruleForm',this.hsl,{deep:true})
  },

  computed: {
    newTableData() {
      return this.tableData.filter((item) => {
        // 判断是否满足phoneModel条件
        let matchPhoneModel = false;
        // 如果phoneModel为”全部“，则所有数据都满足条件
        if (this.phoneModel == '全部') {
          matchPhoneModel = true;
        } else {
          // 根据你的数据结构，item中应该有一个属性是关于type的信息
          // 假设这个属性的名称为'type'
          matchPhoneModel = item.type == this.phoneModel;
        }

        // 判断是否满足seek条件
        let matchSeek = false;
        // 搜索属性 如 'name'  'age'等
        const fieldsToSearch = ['name'];
        // 如果seek为空，那么所有数据都满足条件
        if (!this.seek) {
          matchSeek = true;
        } else {
          // 否则，检查item中的每个字段是否包含seek字符串，如果包含，则返回true
          matchSeek = fieldsToSearch.some((fieldName) => {
            // 使用String(item[fieldName])确保值被正确转换为字符串，否则可能会出现类型错误
            return String(item[fieldName]).includes(this.seek);
          });
        }

        // 如果同时满足phoneModel和seek条件，那么保留这个元素
        return matchPhoneModel && matchSeek;
      });
    },
  },

  methods: {
    //  上传图片函数
    uploadToQiniu(blob, num) {
      const that = this;
      const observable = qiniu.upload(blob, that.key, that.token);
      const observer = {
        complete(res) {
          // 处理上传完成
          if (num == 1) {
            that.ruleForm.icon = res.key;
          } else {
            that.ruleForm.launch = res.key;
          }
          this.$message.success('上传成功');
        },
      };
      observable.subscribe(observer);
    },

    base64ToBlob(base64Data) {
      const arr = base64Data.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    removeDomainFromUrl(url) {
      const domainToRemove = 'https://down.kebei.vip/';

      if (url.startsWith(domainToRemove)) {
        return url.slice(domainToRemove.length);
      }

      // 如果URL不是以指定的域名开始，则原样返回
      return url;
    },

    async handleAvatarSuccess(files, num) {
      const file = files.file;
      const reader = new FileReader();
      const that = this;
      reader.onload = function (readerEvent) {
        var base64 = readerEvent.target.result;
        // 将base64图片转码
        const blob = that.base64ToBlob(base64);
        const options = {
          quality: 0.92,
          noCompressIfLarger: true,
        };
        // 上传图片
        qiniu.compressImage(blob, options).then((data) => {
          const compressedBlob = data.dist;
          that.uploadToQiniu(compressedBlob, num);
        });
        if (num == 1) {
          that.icon = base64;
        } else {
          that.launch = base64;
        }
      };
      reader.readAsDataURL(file);
    },

    async getList() {
      this.tableData = (await app_pack_list()).data.reverse();
    },
    onUpdate(id) {
      this.$confirm('确定发布?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          app_pack_publish({ id });
          this.$message.success('发布成功');
        })
        .catch(() => {});
    },
    //删除
    onDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          app_pack_del({ id });
          this.getList();
        })
        .catch(() => {});
    },
    bytesToMB(fileSizeInBytes) {
      const megabyte = 1024 * 1024; // 1 MB = 1024 KB = 1024 * 1024 Bytes
      const fileSizeInMB = fileSizeInBytes / megabyte;
      // 保留两位小数
      const fileSizeInMBRounded = fileSizeInMB.toFixed(2);
      return `${fileSizeInMBRounded} MB`;
    },
    submitForm(formName) {
      if (this.ruleForm.icon == '' || this.ruleForm.launch == '')
        return this.$message.info('请上传图片及图标');
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.icon = this.removeDomainFromUrl(this.ruleForm.icon);
          this.ruleForm.launch = this.removeDomainFromUrl(this.ruleForm.launch);
          app_pack(this.ruleForm).then((res) => {
            if (res.status == -1) {
              this.$message.info(res.message);
            } else {
              this.$message.success(res.message);
            }
          });
          this.resetForm('ruleForm');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName, done) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false;
      this.ruleForm.icon = '';
      this.ruleForm.launch = '';
      this.launch = '';
      this.icon = '';
      done ? done() : '';
    },
    handleClose(done) {
      // done();
      this.resetForm('ruleForm', done);
    },
  },
};
</script>

<style scoped lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px solid #dcdfe6;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.blue-button {
  background-color: transparent;
  color: #2c56ff;
  border-color: #2c56ff;
}

.red-button {
  background-color: transparent;
  color: #ff4c4c;
  border-color: #ff4c4c;
}

.QRBig {
  width: 80px;
  border-bottom: 1px solid #eef0f6;
  padding: 5px;
  background: #ffffff;
  position: absolute;
  right: 0;
  bottom: 0;
  z-index: 99999;
  display: none;
}

.QRmini:hover + .QRBig {
  display: block;
}

.QRmini {
  position: relative;
  width: 30px;
  margin-left: 5px;
}

.applink {
  display: flex;
  justify-content: center;
  align-content: center;
}

.time {
  font-size: 14px;
  font-weight: 400;
  color: #9094aa;
}

.appBoxRight-top-left {
  font-size: 16px;
  font-weight: 700;
  margin-bottom: 7px;
  color: #000;
}

.Android {
  width: 16px;
}

.app-form {
  margin-left: 5px;
  padding: 0 5px 0 5px;
  color: #ffffff;
}

.ios {
  background-color: #3860f4;
}

.appBoxRight-top {
  display: flex;
}

.appBox {
  display: flex;
}

.appLogo {
  width: 60px;
  height: 60px;
  border-radius: 10px;
  margin-right: 17px;
}

.list {
  width: 1143px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid #eef0f6;
}

.boundary {
  background-color: #aaaebe;
  width: 1px;
  height: 15px;
}

.txt1 {
  font-size: 14px;
  font-weight: 400;
  color: #aaaebe;
}

.big1 {
  width: 350px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.seek {
  margin-left: 30px;
}

.search {
  width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  height: 86px;
  align-items: center;
}

.head {
  height: 200px;
  background: url(../../assets/tfsign.png);
}

.content {
  width: 1200px;
  height: 200px;
  margin: 0 auto;
  position: relative;
  display: flex;
  justify-content: flex-end;
  overflow: hidden;
}

.textimg {
  width: 290px;
  height: 62px;
  position: absolute;
  left: 0;
  bottom: 20px;
}

.btns {
  margin-top: 48px;
  text-align: center;
}

.shop {
  color: #2c56ff;
  background: #e3e9ff;
  margin-right: 20px;
}

.upload {
  background: #2c56ff;
  color: #ffffff;
}

.circle {
  position: absolute;
  right: 0;
  bottom: -220px;
  width: 480px;
  height: 320px;
  background: #fafbff;
  border-radius: 50%;
}
.info {
  display: flex;
  flex: 1;
  .item {
    width: 76%;
    display: flex;
    flex-direction: column;
    align-items: center;
    border-right: 1px solid #ddd;

    > * {
      height: calc(100% / 3);
    }

    &:last-child {
      border-right: none;
    }
    &:last-child::after {
      display: block;
      width: 0;
      height: calc(100% / 3);
      content: '';
    }
  }
}
.red {
  margin-top: 10px;
  color: rgb(236, 79, 79);
  font-size: 18px;
}
</style>
